import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { Camera, CameraOptions } from '@ionic-native/camera/ngx';
import { CacheService } from './cache.service';
import { DataService } from './data.service';
import { File } from '@ionic-native/file/ngx';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { Observable } from 'rxjs';
import { NativeService } from './native.service';

declare var window;

@Injectable({
    providedIn: 'root',
})
export class PicUploadService {

    constructor(private camera: Camera,
        public dataService: DataService,
        public transfer: FileTransfer,
        private file: File,
        public cache: CacheService,
        public nativeService: NativeService,
        private platform: Platform,
    ) { }

    GetPic(sourse): any {
        if (sourse === 0) {
            return this.getCamera();
        }
        if (sourse === 1) {
            return this.getLib();
        }
    }

    // 拍照上传
    getCamera() {
        console.log('Camera');
        const options: CameraOptions = {
            quality: 100,
            allowEdit: true,
            targetWidth: 180,
            targetHeight: 180,
            saveToPhotoAlbum: true,
            sourceType: this.camera.PictureSourceType.CAMERA,
            destinationType: this.camera.DestinationType.FILE_URI,
        };
        return this.camera.getPicture(options).then(imageData => {
            return imageData;
        }, error => {
            alert('图片获取失败');
        });
    }

    //  相册获取图片
    getLib() {
        console.log('Lib');
        const options: CameraOptions = {
            quality: 100,
            allowEdit: true,
            targetWidth: 180,
            targetHeight: 180,
            saveToPhotoAlbum: true,
            sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
            destinationType: this.camera.DestinationType.FILE_URI,
        };
        return this.camera.getPicture(options).then(imageData => {
            console.log(imageData);
            return imageData;
        }, error => {
            alert('图片获取失败');
        });
    }



    /**
     * 获取头像
     *  判断有没有远程
       *    否：用默认头像
       *    是：判断有没有本地路径
       *        否：下载
       *        是：判断远程路径跟本地下载的头像是否一致
       *	        否：重新下载，修改本地路径，并使用本地路径
       *	        是：判断本地路径是否真的头像资源
       *		        否：重新下载，修改本地路径，并使用本地路径
       *		        是：使用本地路径
     */
    getAvatar(): Observable<any> {
        return new Observable(responseObserver => {
            const defaultAvatar = { url: 'assets/imgs/default.png', isDefault: true };
            const httpAvatar = this.cache.userinfo.avatar;
            let localAvatar; localAvatar = this.cache.headPortrait;
            if (!httpAvatar) {
                responseObserver.next(defaultAvatar);
                responseObserver.complete();
            } else if (!localAvatar) {
                console.log('没有本地的路径，下载头像');
                const path = this.getBasePath() + 'avatar/' + new Date().getTime() + '.png';
                this.download(httpAvatar, path).subscribe(res => {
                    responseObserver.next(res);
                    responseObserver.complete();
                });
            } else if (localAvatar.oldAvatar !== httpAvatar) {
                console.log('有本地但是远程的更新，重新下载');
                const path = this.getBasePath() + 'avatar/' + new Date().getTime() + '.png';
                this.download(httpAvatar, path).subscribe(res => {
                    responseObserver.next(res);
                    responseObserver.complete();
                });
            } else {
                console.log('本地有路径，并且和远程的资源一致');
                let img; img = new Image();
                img.src = localAvatar.avatar;
                img.onload = () => {
                    responseObserver.next({ url: localAvatar.avatar, isDefault: false });
                    responseObserver.complete();
                };
                img.onerror = () => {
                    const path = this.getBasePath() + 'avatar/' + new Date().getTime() + '.png';
                    this.download(httpAvatar, path).subscribe(res => {
                        responseObserver.next(res);
                        responseObserver.complete();
                    });
                };
            }
        });

    }

    /**
     * 头像下载
     * @param remotePath 远程地址
     * @param targetPath 本地存储路径
     */
    download(remotePath, targetPath, isToURL?): Observable<any> {
        return new Observable(responseObserver => {
            if (window.cordova) {           // 移动端
                console.log('开始下载');
                this.nativeService.filedownload(remotePath, targetPath, isToURL).then(url => {
                    console.log('下载成功,转换前的路径', url);
                    const imgsrc = isToURL ? url : window.Ionic.WebView.convertFileSrc(url); // 要转换一下，否则不允许加载本地资源加载
                    console.log('图片下载成功，转换后的路径', imgsrc);
                    this.cache.headPortrait = { oldAvatar: remotePath, avatar: imgsrc };
                    responseObserver.next({ url: imgsrc, isDefault: false });
                    responseObserver.complete();
                }).catch(err => {
                    console.log('下载出错', err);
                    responseObserver.next({ url: 'assets/imgs/default.png', isDefault: true });
                    responseObserver.complete();
                });
            } else {                        // 浏览器
                this.cache.headPortrait = { oldAvatar: remotePath, avatar: remotePath };
                let img; img = new Image();
                img.src = remotePath;
                img.onload = () => {
                    responseObserver.next({ url: remotePath, isDefault: false });
                    responseObserver.complete();
                };
                img.onerror = () => {
                    responseObserver.next({ url: 'assets/imgs/default.png', isDefault: true });
                    responseObserver.complete();
                };
            }

        });
    }

    /**
     * 头像上传
     * @param filePath 文件路径
     * @param options 参数
     */
    upload(filePath, options): Observable<any> {
        return new Observable(responseObserver => {
            const serverCode = 15;
            const apiCode = 200000;
            const serviceAddr = this.cache.getUrl(serverCode, apiCode).serviceAddr;
            const apiAddr = this.cache.getUrl(serverCode, apiCode).apiAddr;
            this.nativeService.fileUpload(filePath, serviceAddr + apiAddr, options).then(data => {
                responseObserver.next({ data: data, ip: serviceAddr });
                responseObserver.complete();
            }).catch((data) => {
                responseObserver.error({ data: data, ip: serviceAddr });
                responseObserver.complete();
            });
        });
    }

    getBasePath(noFile?) {
        let basePath;
        if (this.platform.is('ios')) {
            if (noFile === true) {
                basePath = this.file.documentsDirectory.replace('file://', '');
            } else {
                basePath = this.file.documentsDirectory;
            }
        } else {
            basePath = this.file.externalApplicationStorageDirectory || this.file.applicationStorageDirectory;
        }
        return basePath;
    }

}
